/*
 * Copyright (c) 2013 Andaily Information Technology Co. Ltd
 * www.andaily.com
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * Andaily Information Technology Co. Ltd ("Confidential Information").
 * You shall not disclose such Confidential Information and shall use
 * it only in accordance with the terms of the license agreement you
 * entered into with Andaily Information Technology Co. Ltd.
 */
package top.suven.http.oauth.token;

import com.alibaba.fastjson.JSONObject;
import org.apache.oltu.oauth2.as.request.AbstractOAuthTokenRequest;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.OAuthResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.suven.base.util.utilize.JsonUtils;

/**
 * @ClassName: OAuthTokenHandleDispatcher.java
 * @Description: OAUTH2.0的认证服务, auth 请求验证 grant_type=authorization_code
 * @Author suven.wang
 * @Date 2018/7/26 18:01
 * @Copyright: (c) 2018 gc by https://www.gc.com.cn/
 * @Version : 1.0.0
 *  --------------------------------------------------------
 *  modifyer    modifyTime                 comment
 *
 *  --------------------------------------------------------
 */
public class OAuthTokenHandleDispatcher {

    private static final Logger LOG = LoggerFactory.getLogger(OAuthTokenHandleDispatcher.class);

    private final AbstractOAuthTokenRequest tokenRequest;

    public OAuthTokenHandleDispatcher(AbstractOAuthTokenRequest tokenRequest) {
        this.tokenRequest = tokenRequest;
    }


    public OAuthResponse dispatch() throws OAuthProblemException, OAuthSystemException {

        final String grantType = tokenRequest.getGrantType();
        OAuthTokenHandler handler = OAuthHandlerUtils.getOAuthTokenHandler(grantType);
        if (null != handler && handler.support(tokenRequest)) {
            LOG.debug("Found '{}' handle OAuthTokenxRequest: {}", handler, tokenRequest);
            OAuthResponse response = handler.handle(tokenRequest);
            return response;
        }
        throw new IllegalStateException("Not found 'OAuthTokenHandler' to handle OAuthTokenxRequest: " + tokenRequest);
    }

    public JSONObject getResponse(OAuthResponse response){
        if(null == response){
            return null;
        }
        return JsonUtils.readValue(response.getBody(),JSONObject.class);
    }

}
